package com.slowfly.rule.engine.features;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.slowfly.rule.engine.constants.IRiskConstants;
import com.slowfly.rule.engine.entity.Feature;
import com.slowfly.rule.engine.enums.FeatureTypeEnum;
import com.slowfly.rule.engine.param.ListFeaturesParam;
import com.slowfly.rule.engine.util.GroovyScriptUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;


@Slf4j
public abstract class BaseFeatureClass {

    public abstract Object getFeatureValue(ListFeaturesParam param, Feature feature);

    protected Object getFeatureValue(Object riskParam, String path) {
        try {
            String scripts = String.format(IRiskConstants.FEATURE_SCRIPT_FORMAT, path);
            return GroovyScriptUtil.invokeMethod(scripts, IRiskConstants.FEATURE_SCRIPT_METHOD, new Object[]{riskParam});
        } catch (Exception e) {
            log.error("getFeatureValue error {} {}", path, JSON.toJSON(riskParam), e);
        }
        return null;
    }

    protected Object convertFeatureType(Object featureValue, Integer featureType) {
        if (Objects.isNull(featureValue)) {
            return null;
        }
        String str = featureValue.toString().trim();
        if (FeatureTypeEnum.NUMBER.getCode().equals(featureType)) {
            if (featureValue instanceof Number) {
                return featureValue;
            }
            if (featureValue instanceof Date) {
                return ((Date) featureValue).getTime();
            }
            if (NumberUtil.isInteger(str)) {
                return new Integer((String) featureValue);
            }
            if (NumberUtil.isLong(str)) {
                return new Long((String) featureValue);
            }
            if (NumberUtil.isDouble(str)) {
                return new Double((String) featureValue);
            }
        }
        if (FeatureTypeEnum.STRING.getCode().equals(featureType)) {
            return str;
        }
        if (FeatureTypeEnum.BOOLEAN.getCode().equals(featureType)) {
            if (featureValue instanceof Boolean) {
                return featureValue;
            }
            if (featureValue instanceof String) {
                return "true".equals(str) || "1".equals(str);
            }
            if (featureValue instanceof Integer || featureValue instanceof Long) {
                return (int) featureValue == 1;
            }
        }
        return null;
    }

}
